<template>
  <el-container class="template-layout">
    <!-- 顶部查询：字段暂留，后续补齐 -->
    <el-header v-if="showSearchHeader">
      <zz-Search
        :searchOptions="searchOptions"
        :loading="loading"
        @getSearchData="getSearchData"
        @resetFields="resetFields"
      />
    </el-header>

    <el-main>
      <!-- 工具栏与右侧操作：表格尺寸/显示查询/列设置 -->
      <zz-PageBar>
        <template #buttons>
          <el-button type="primary" @click="addItem">{{ $t('common.add') }}</el-button>
          <el-button type="danger" @click="delItems" plain>{{ $t('common.delete') }}</el-button>
        </template>
        <template #right>
          <el-dropdown @command="handleSizeChange">
            <el-button :icon="'Switch'" circle />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="mini">{{ $t('table.mini') }}</el-dropdown-item>
                <el-dropdown-item command="small">{{ $t('table.small') }}</el-dropdown-item>
                <el-dropdown-item command="medium">{{ $t('table.medium') }}</el-dropdown-item>
                <el-dropdown-item command="large">{{ $t('table.large') }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button :icon="'Search'" circle @click="showSearchHeader = !showSearchHeader" />
          <el-button :icon="'Operation'" circle @click="showColumnSetting = true" />
        </template>
      </zz-PageBar>

      <!-- 表格：列与字段暂留不写，后续补齐 -->
      <zz-Table
        ref="tableRef"
        :key="tableKey"
        :data="tableData"
        :page="tablePage"
        :hasPage="true"
        :size="tabelSize"
        :loading="loading"
      >
        <vxe-column type="checkbox" fixed="left" width="40" />
        <vxe-column type="seq" fixed="left" width="50" />

        <!-- 动态列渲染：根据 tableColumns -->
        <template v-for="column in tableColumns" :key="column.field">
          <vxe-column
            v-if="column.visible"
            :field="column.field"
            :title="column.title"
            :fixed="column.fixed"
            :width="150"
          >
            <template #default="{ row }">
              {{ row[column.field] }}
            </template>
          </vxe-column>
        </template>

        <!-- 操作列：占位逻辑，后续接入真实业务 -->
        <vxe-column :title="$t('common.operation')" :width="200" fixed="right">
          <template v-slot="{ row }">
            <zz-TableBtn type="text" :loading="btnLoading" @click="viewItem(row)">{{ $t('common.view') }}</zz-TableBtn>
            <zz-TableBtn type="error" :loading="btnLoading" @click="delItem(row)">{{ $t('common.delete') }}</zz-TableBtn>
          </template>
        </vxe-column>
      </zz-Table>
    </el-main>
  </el-container>

  <!-- 业务组件 -->

  <!-- 列设置：使用本地存储，键名 testManagement_columns；默认列暂留不写 -->
  <zz-ColumnSetting
    v-model="showColumnSetting"
    :columns="tableColumns"
    :default-columns="defaultTableColumns"
    storage-key="testManagement_columns"
    list-id="testManagement-column-list"
    drawer-class="testManagement-column-setting-drawer"
    @confirm="handleColumnConfirm"
    @cancel="handleColumnCancel"
    @reset="handleColumnReset"
  />
</template>

<script setup>
// 说明：
// 1) 字段与列属性暂留不写，后续填充真实测试领域字段
// 2) 与业务/义务相关逻辑（接口、增删改查）均为占位，后续接入

import { computed, getCurrentInstance, onMounted, ref } from 'vue';
const { proxy } = getCurrentInstance();

// UI 状态
const showSearchHeader = ref(true);
const showColumnSetting = ref(false);

// 查询模型与配置（暂留）
const searchModel = ref({});
const searchOptions = computed(() => ({
  model: searchModel,
  // 查询表单列暂留，后续按测试管理需求补齐
  column: [],
}));

// 查询事件
const getSearchData = (val) => {
  searchModel.value = val;
  query('search');
};
// 重置查询表单
const resetFields = () => {
  // 清空查询模型（具体字段稍后补齐）
  searchModel.value = {};
};

// 表格与分页
const tableData = ref([]);
const tablePage = ref({ pageNum: 1, pageSize: 15, total: 0 });
const tabelSize = ref('small');
const tableRef = ref(null);

// 处理表格大小变化
const handleSizeChange = (size) => { tabelSize.value = size; };

// 列配置与本地存储键
const STORAGE_KEY = proxy.$CONS.STORAGE_KEY;
const tableKey = ref(0);

// 当前列配置与默认列（暂留空，后续补齐）
const tableColumns = ref([]);
const defaultTableColumns = ref([]);

// 处理列设置确认
const handleColumnConfirm = (columns) => {
  tableColumns.value = JSON.parse(JSON.stringify(columns));
  const all = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
  all['testManagement_columns'] = tableColumns.value;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
  tableKey.value += 1;
};
// 处理列设置取消
const handleColumnCancel = () => { loadColumnSettings(); };
// 处理列设置重置
const handleColumnReset = (columns) => {
  tableColumns.value = JSON.parse(JSON.stringify(columns));
  const all = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
  all['testManagement_columns'] = tableColumns.value;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
  tableKey.value += 1;
};

// 加载已保存列设置
const loadColumnSettings = () => {
  try {
    const saved = JSON.parse(localStorage.getItem(STORAGE_KEY))?.['testManagement_columns'];
    if (saved) tableColumns.value = saved;
    tableKey.value += 1;
  } catch (e) {
    console.error('加载列设置失败:', e);
  }
};

// 查询（占位：后续接入测试管理相关接口）
const loading = ref(false);
const btnLoading = ref(false);

const query = async (mode) => {
  loading.value = true;
  if (mode === 'search') {
    searchModel.value.queryParam = { pageNum: 1, pageSize: 15, total: 0 };
  }
  // TODO: 接入测试管理查询接口，替换为真实 API
  let params = dealParams();
  const res = await proxy.$API.testManagement.xxx.queryWithPage.post(params);
  if (res.code === '01') { 
    tableData.value = res.bizList; 
    tablePage.value.total = res.total; 
    tablePage.value.pageSize = res.pageSize;
  }
  loading.value = false;
};
// 处理查询参数
const dealParams = () => {
    let params = {
    ...searchModel.value,
  };

  // 其他的参数转化逻辑，如日期格式等
  return params
}

// 业务操作占位（后续接入真实逻辑）
const addItem = () => { proxy.$message.info('新增功能待实现'); };
const delItems = async () => {
  const rows = tableRef.value?.getCheckboxRecords?.() || [];
  if (rows.length === 0) return proxy.$message.warning('请选择要删除的记录');
  proxy.$message.info('批量删除功能待实现');
};
const delItem = async (row) => { proxy.$message.info('单条删除功能待实现'); };
const viewItem = (row) => { proxy.$message.info('查看功能待实现'); };
const editItem = (row) => { proxy.$message.info('编辑功能待实现'); };

onMounted(() => {
  loadColumnSettings();
  query('search');
});
</script>